#! -*- coding:utf-8 -*-

import math
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
import sys, os, time, uuid, re, codecs
import urllib2
import chardet
from bs4 import BeautifulSoup
from pymongo import MongoClient
import cPickle
import stock_data

#给K先矩阵设置买卖标签
def buildLabel(prices,data):
    labels = []
    lens = shape(data)[0]
    for i in range(lens):
        label = 0
        if isBuy(prices,data, i):
            label = 1
        elif isSale(prices,data, i):
            label = 2
        labels.append(label)
    return labels


#购买信号
def isBuy(prices,data,index):
    asc = False
    index=index-1
    if data[index,0]>data[index,1] and data[index,1]>data[index,2] and data[index,2]>data[index,3]:
        asc = True
    #if (prices[index+1][1]> 1.04 * prices[index][3]):
    #    asc = False
    return asc

def isSale(prices,data,index):
    desc = False
    index=index-1
    if data[index, 0] < data[index, 1] and data[index, 1] < data[index, 2] and data[index, 2] < data[index, 3]:
        desc = True
    #if (prices[index+1][1] < 0.96 * prices[index][3]):
    #    desc = False
    return desc

# #平仓多单
# def isEvenBuy(prices,data,index):
#     delta=0.02
#     if data[index,0]<data[index,1] and data[index-2,0]-data[index,1]>delta*data[index,0]:
#         return True
#     return False
#
# def isEvenSale(prices,data,index):
#     delta = 0.02
#     if data[index, 0] > data[index, 1] and data[index , 0] - data[index - 2, 0] > delta * data[index, 0]:
#         return True
#     return False

def getOneMatrix(kind):
    (prices, data) = stock_data.getTrainingData(kind)
    mats = mat(data)
    prices=mat(prices)
    labels = mat(buildLabel(prices, mats))
    print "get kind:",kind
    #print "mat shape:", shape(mats),",price:",shape(prices), ",labels:", shape(labels.T)
    data = hstack((prices,data,labels.T))
    print data[1]
    print "getOneMatrix shape:",shape(data)
    return data

def getCurrentMoney(money,kind,dict,currentprice,shouxu):
    if dict.has_key(kind):
        label = dict[kind][1]
        lastprice = dict[kind][2]
        count = dict[kind][3]
        if label == 1:
            money = money + count * (currentprice - lastprice) - shouxu
        elif label==2:
            money = money - count * (currentprice - lastprice) - shouxu
    return money

#验证单个品种的资金曲线
def validateData(kind,mats,doubles=1):
    print "开始验证收益率"
    money = 100000
    count = doubles*money/mats[4,4]
    shouxu = count * 0
    lens = shape(mats)[0]

    dict={}
    trades = []
    trades.append(money)
    #index = getIndex(prices, '2010-10-08')
    #if (len(index)==1):
    #    print "2010-10-08:", prices[index[0]]
    for index in range(1,lens):
        label=mats[index-1,9]
        tm = mats[index,0]
        open_price = mats[index,1]
        high_price = mats[index,2]
        low_price =mats[index,3]
        close_price = mats[index,4]
        ma1 = mats[index-1,5]
        ma2 = mats[index-1,6]
        ma3=mats[index-1,7]
        ma4 = mats[index-1,8]
        #print "current tm:",tm,",close_price:",close_price,",label:",label
        if label == 1 :
            print "got 1"
            if not dict.has_key(kind):
                dict[kind]=[tm,label,open_price,count]
                print "index:",index,"buy prcice:",open_price
        elif label == 2:
            if not dict.has_key(kind):
                dict[kind] = [tm,label, open_price,count]
                print "index:",index,"sale prcice:", open_price
        else:
            if dict.has_key(kind):
                label = dict[kind][1]
                lastprice = dict[kind][2]
                count = dict[kind][3]
                if label ==1:
                    money = money+count*(close_price-lastprice)-shouxu
                    print "index:",index,"even price:",close_price,"owning:",count *(close_price-lastprice)
                elif label==2:
                    money = money -count*( close_price - lastprice) - shouxu
                    print "index:",index,"even price:",close_price,"owning:", 0-count*( close_price - lastprice)
                dict.clear()
        curmoney=getCurrentMoney(money,kind,dict,close_price,shouxu)
        trades.append(curmoney)
    #print trades
    perrecude = 0.01
    dt=np.matrix(trades)
    print "dt shape:",shape(dt)
    lens = len(trades)
    for i in range(lens-1):
        #print min(trades[i+1:lens]) #np.min(dt[:,index:-1])
        if min(trades[i+1:lens])<trades[i]*(1-perrecude):
            perrecude=(trades[i]-min(trades[i+1:lens]))/(trades[i])
    print "mintrade:",min(trades),",perreduce:",perrecude
    return trades


# #验证收益率
# def validate(begin=2,lens=100):
#     print "开始验证收益率"
#     money = 100000
#     doubles=2
#     end = begin + lens
#     mats = []
#     trades = []
#     dict = {}
#
#     (prices, data) = getStrateryData('RU0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     print "RU length:",len(prices)
#     labels = buildLabel(prices,mat)
#     count = doubles * (money / data[3][1]) #math.ceil(money / data[3][1])
#     shouxu = count * 0
#     mats.append([prices, data, labels, count, shouxu,'RU0'])
#
#     (prices, data) = getStrateryData('AG0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     labels = buildLabel(prices, mat)
#     count = doubles * (money / data[3][1])
#     shouxu = count * 2
#     #mats.append([prices, data, labels, count, shouxu,'AG0'])
#
#     (prices, data) = getStrateryData('CU0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     labels = buildLabel(prices, mat)
#     count = doubles * (money / data[3][1])
#     shouxu = count * 2
#     mats.append([prices,data,labels,count,shouxu,'CU0'])
#
#     (prices, data) = getStrateryData('ZN0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     labels = buildLabel(prices, mat)
#     count = doubles * (money / data[3][1])
#     shouxu = count * 2
#     #mats.append([prices, data, labels, count, shouxu,'ZN0'])
#
#     (prices, data) = getStrateryData('M0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     labels = buildLabel(prices, mat)
#     count = doubles * (money / data[3][1])
#     shouxu = count * 2
#     #mats.append([prices, data, labels, count, shouxu,'M0'])
#
#     (prices, data) = getStrateryData('Y0')  # getPrices('RU0')   # data = getPrices('RU60t')
#     mat = np.matrix(data)
#     labels = buildLabel(prices, mat)
#     count = doubles * (money / data[3][1])
#     shouxu = count * 2
#     #mats.append([prices, data, labels, count, shouxu,'Y0'])
#
#     for index in range(begin, end):
#
#         for i in range(len(mats)):
#             row = mats[i]
#             kind = row[5]
#             prices = row[0]
#             data = row[1]
#             labels = row[2]
#             count = row[3]
#             shouxu = row[4]
#             if (len(prices) - 30 < index):
#                 continue
#             #count=(doubles * money) / (prices[index-1][4])
#             if labels[index] == 1:
#                 if not dict.has_key(kind):
#                     dict[kind] = [labels[index], prices[index][1],count]
#                     print "index:", index, "buy prcice:", prices[index][1]
#                     # money =afterbuyit(prices,mat,index,money,shouxu) #money + (count * (prices[index][4] - prices[index][1])) - shouxu
#             elif labels[index] == 2:
#                 if not dict.has_key(kind):
#                     dict[kind] = [labels[index], prices[index][1],count]
#                     print "index:", index, "sale prcice:", prices[index][1]
#                     # money = aftersaleit(prices, mat, index, money, shouxu) #money = money - (count * (prices[index][4] - prices[index][1])) - shouxu
#             else:
#                 if dict.has_key(kind):
#                     if dict[kind][0] == 1:
#                         money = money + dict[kind][2] * (prices[index][4] - dict[kind][1]) - shouxu
#                         print "index:", index, "even buy:", prices[index][4]
#                     else:
#                         money = money - dict[kind][2] * (prices[index][4] - dict[kind][1]) - shouxu
#                         print "index:", index, "even sale:", prices[index][4]
#                     dict.clear()
#
#             trades.append(money)
#
#     print trades
#     perrecude = 0.01
#     dt = np.matrix(trades)
#     print "dt shape:", shape(dt)
#     lens = len(trades) - 1
#     for i in range(lens - 1):
#         print min(trades[i + 1:lens])  # np.min(dt[:,index:-1])
#         if min(trades[i + 1:lens]) < trades[i] * (1 - perrecude):
#             perrecude = (trades[i] - min(trades[i + 1:lens])) / (trades[i])
#     print "mintrade:", min(trades), ",perreduce:", perrecude
#     return trades
#
#
# def validateSingle(kind,doubles=1):
#     print "开始验证收益率"
#     money = 100000
#     dict={}
#
#     trades = []
#     (prices, data) = getStrateryData(kind)  # getPrices('RU0')   # data = getPrices('RU60t')
#     index = getIndex(prices, '2010-10-08')
#     if (len(index)==1):
#         print "2010-10-08:", prices[index[0]]
#     end = min(3000,len(prices)-2)
#     mat = np.matrix(data)
#     print "length:",len(prices)
#     labels = buildLabel(prices,mat)
#     #print "labels:",labels
#     count = doubles * money / prices[3][1] #math.ceil(money / data[3][1])
#     bakcount=count
#     shouxu = 0
#
#     for index in range(200, end):
#         #count=(doubles * money) / (prices[index-1][4])
#         if (money>200000):
#             count=bakcount*2
#         if (money > 300000):
#             count = bakcount*3
#         if (money > 400000):
#             count = bakcount * 4
#         if labels[index] == 1 :
#             if not dict.has_key(kind):
#                 dict[kind]=[labels[index],prices[index][1]]
#                 print "index:",index,"buy prcice:",prices[index][1]
#             #money =afterbuyit(prices,mat,index,money,shouxu) #money + (count * (prices[index][4] - prices[index][1])) - shouxu
#         elif labels[index] == 2:
#             if not dict.has_key(kind):
#                 dict[kind] = [labels[index], prices[index][1]]
#                 print "index:",index,"sale prcice:", prices[index][1]
#             #money = aftersaleit(prices, mat, index, money, shouxu) #money = money - (count * (prices[index][4] - prices[index][1])) - shouxu
#         else:
#             if dict.has_key(kind):
#                 if dict[kind][0]==1:
#                     money = money+count*(prices[index][4]-dict[kind][1])-shouxu
#                     print "index:",index,"even price:",prices[index][4],"owning:",prices[index][4]-dict[kind][1]
#                 else:
#                     money = money -count*( prices[index][4] - dict[kind][1]) - shouxu
#                     print "index:",index,"even price:",prices[index][4],"owning:", 0-count*( prices[index][4] - dict[kind][1])
#                 dict.clear()
#         trades.append(money)
#     print trades
#     perrecude = 0.01
#     dt=np.matrix(trades)
#     print "dt shape:",shape(dt)
#     lens = len(trades)
#     for i in range(lens):
#         print min(trades[i+1:lens]) #np.min(dt[:,index:-1])
#         if min(trades[i+1:lens])<trades[i]*(1-perrecude):
#             perrecude=(trades[i]-min(trades[i+1:lens]))/(trades[i])
#     print "mintrade:",min(trades),",perreduce:",perrecude
#     return trades


# #日内操作
# def validateSingle_EveryDay(kind):
#     print "开始验证收益率"
#     money = 100000
#     doubles=1
#     dict={}
#
#     trades = []
#     (prices, data) = getStrateryData(kind)  # getPrices('RU0')   # data = getPrices('RU60t')
#     end = min(3000,len(prices)-30)
#     mat = np.matrix(data)
#     print "724 date:",prices[734][0]
#     print "length:",len(prices)
#     labels = buildLabel(prices,mat)
#     print "labels:",labels
#     count = doubles * money / prices[3][1] #math.ceil(money / data[3][1])
#     bakcount=count
#     print "price:", data[3][1],"count:",count
#     shouxu = 0
#
#     for index in range(2, end):
#         #count=(doubles * money) / (prices[index-1][4])
#         if (money>200000):
#             count=bakcount*2
#         if (money > 300000):
#             count = bakcount*3
#         if (money > 400000):
#             count = bakcount * 4
#         if labels[index] == 1 :
#             money = money + count * (prices[index][4] -prices[index][1]) - shouxu
#         elif labels[index] == 2:
#             money = money - count * (prices[index][4] - prices[index][1]) - shouxu
#         trades.append(money)
#     print trades
#     perrecude = 0.01
#     dt=np.matrix(trades)
#     print "dt shape:",shape(dt)
#     lens = len(trades)-1
#     for i in range(lens-1):
#         print min(trades[i+1:lens]) #np.min(dt[:,index:-1])
#         if min(trades[i+1:lens])<trades[i]*(1-perrecude):
#             perrecude=(trades[i]-min(trades[i+1:lens]))/(trades[i])
#     print "mintrade:",min(trades),",perreduce:",perrecude
#     return trades


if __name__ == "__main__":
    print "begin auto trade..."
    #Y0/CF0/L0等几个品种不规律，RU0，CU0，RB0，J0等比较有规律
    kinds =['RU0','CU0','RB0','J0','M0','Y0']
    for index in range(len(kinds)):
        kind = kinds[index]
        mats = getOneMatrix(kind)
        trades = validateData(kind, mats, doubles = 3 )
        plt.style.use('ggplot')
        plt.title(kind)
        plt.ylabel('Price Value')
        plt.xlabel('Time')
        plt.plot(trades[0:-1], 'r')
        plt.tight_layout()
        plt.show()

